package com.kfm.login.util;


import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.kfm.login.model.response.IPAddress;

import javax.servlet.http.HttpServletRequest;

public class IPUtils {

    /**
     * 通过请求获取IP地址
     * @param request  http请求
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
        }
    }


    public static IPAddress getLocation(String ip) {
        String ak = "ovdC6vd646XSRBEtPcBaLqltSRIkmbdE";
        String url = "https://api.map.baidu.com/location/ip?coor=bd09ll&ak=" + ak + ("127.0.0.1".equals(ip) ? "" : "&ip=" + ip);
        String body = HttpRequest.get(url).execute().body();
        return JSONUtil.toBean(body, IPAddress.class);
    }
}

